const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const glob = require("glob");
const fs = require("fs");

// 使用 glob 获取 src 目录下所有 HTML 文件路径，包括子目录
// const htmlFiles = glob.sync(path.resolve(__dirname, "src", "**", "*.html"));
const htmlFiles = glob.sync(
  path.resolve(__dirname, "src", "**", "*.html").replace(/\\/g, "/")
);

// 动态生成 entry 配置
const entry = {};
htmlFiles.forEach((filePath) => {
  const entryName = path
    .relative(path.resolve(__dirname, "src"), filePath)
    .replace(/\.html$/, "");
  const entryChunk = `${filePath.replace(/\.html$/, ".js")}`;
  // 是否存在入口文件 (入口js文件必须和当前html文件名一致, 如果没有入口文件就不需要写js文件)
  if (fs.existsSync(entryChunk)) {
    entry[entryName] = entryChunk;
  }
});

// 动态生成 plugins 配置
const plugins = htmlFiles.map((filePath) => {
  const entryName = path
    .relative(path.resolve(__dirname, "src"), filePath)
    .replace(/\.html$/, "");

  return new HtmlWebpackPlugin({
    template: ".\\src" + filePath.split("src")[1],
    filename: `${entryName}.html`,
    chunks: [entryName],
  });
});
module.exports = {
  entry,
  htmlPlugins: plugins,
  // 其他配置...
};
